/*
 * Copyright (C) 拾光分享网 
 * All rights reserved, Designed By www.hiai.top.
 * Email：goodsking@163.com.
 * Version：V1.0.2(20230701).
 */
package top.hiai.login;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.kit.Ret;
import top.hiai.common.util.IpKit;
import top.hiai.common.util.SensitiveWordsKit;
import top.hiai.config.BaseController;

import java.io.IOException;

/**
 * @Author www.hiai.top
 * @Email goodsking@163.com
 * @Message 更多资源尽在www.hiai.top
 * @Introduction 类的介绍
 */
public class LoginController extends BaseController {

    LoginService loginService = new LoginService();

    /**
     * 渲染用户登录界面
     */
    public void index() {
        /**  保持住 returnUrl 这个参数，以便在登录成功后跳转到该参数指向的页面*/
        keepPara("returnUrl");
        render("index.html");
    }

    /**
     * 渲染注册用户界面
     */
    public void register() {
        render("register.html");
    }

    /**
     * 登录验证
     */
    @Before(LoginValidator.class)
    public void doLogin() {
        //获取用户是否记住登录
        boolean keepLogin = getParaToBoolean("keepLogin", false);
        String loginIp = IpKit.getRealIp(getRequest());
        Ret ret = loginService.login(getPara("email"), getPara("password"), keepLogin, loginIp);
        if (ret.isOk()) {
            String sessionId = ret.getStr(LoginService.sessionIdName);
            int maxAgeInSeconds = ret.getInt("maxAgeInSeconds");
            setCookie(LoginService.sessionIdName, sessionId, maxAgeInSeconds, true);
            setAttr(LoginService.loginAccountCacheName, ret.get(LoginService.loginAccountCacheName));
            // 如果 returnUrl 存在则跳过去，否则跳去首页
            ret.set("returnUrl", getPara("returnUrl", "/"));
        }
        renderJson(ret);
    }

    /**
     * 注册验证
     *
     * @throws IOException
     */
    @Before(LoginValidator.class)
    public void doRegister() throws IOException {
        String nickName = getPara("nickName");
        if (SensitiveWordsKit.checkSensitiveWord(nickName) != null) {
            renderJson(Ret.fail().set("msg", "昵称中不能包含敏感词"));
            return;
        }
        Ret ret = loginService.register(nickName, getPara("email"), getPara("password"));
        if (ret.isOk()) {
            ret.set("returnUrl", "/login");
        }
        renderJson(ret);
    }

    /**
     * 退出登录
     */
    @Clear
    @ActionKey("/logout")
    public void logout() {
        loginService.logout(getCookie(LoginService.sessionIdName));
        removeCookie(LoginService.sessionIdName);
        redirect("/");
    }
}